<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="function,promise," />





  <link rel="alternate" href="/atom.xml" title="二羊的小窝仔" type="application/atom+xml" />






<meta name="description" content="函数式编程 对运算过程进行抽象，用来描述数据(函数)的映射 不是程序中的方法，而是数学中的函数   函数是一等公民：  函数可以存在变量中  123let fn &#x3D; function()&amp;#123;   console.log(&amp;#x27;hello&amp;#x27;)&amp;#125;">
<meta property="og:type" content="article">
<meta property="og:title" content="函数式编程与 JS 异步编程">
<meta property="og:url" content="https://eryangboy.github.io/notes/notes/functional-programming/index.html">
<meta property="og:site_name" content="二羊的小窝仔">
<meta property="og:description" content="函数式编程 对运算过程进行抽象，用来描述数据(函数)的映射 不是程序中的方法，而是数学中的函数   函数是一等公民：  函数可以存在变量中  123let fn &#x3D; function()&amp;#123;   console.log(&amp;#x27;hello&amp;#x27;)&amp;#125;">
<meta property="og:locale">
<meta property="og:image" content="https://eryangboy.github.io/notes/notes/functional-programming/img/EventLoop.jpg">
<meta property="og:image" content="https://eryangboy.github.io/notes/notes/functional-programming/img/TaskQueue.jpg">
<meta property="article:published_time" content="2020-12-12T08:34:41.000Z">
<meta property="article:modified_time" content="2020-12-12T08:37:29.020Z">
<meta property="article:author" content="二羊">
<meta property="article:tag" content="function">
<meta property="article:tag" content="promise">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://eryangboy.github.io/notes/notes/functional-programming/img/EventLoop.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://eryangboy.github.io/notes/notes/functional-programming/"/>





  <title>函数式编程与 JS 异步编程 | 二羊的小窝仔</title>
  








  <script type="text/javascript" src="/js/src/clicklove.js"></script>
<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title" >
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="with-love" id="animate" style='position: relative;
    left: -4px;
    top: 7px;'> 
          <i class="fa fa-heart"></i>
        </span>
        <span class="site-title">二羊的小窝仔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">无需凭借谁的光，我就是自己的太阳</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            笔记
          </a>
        </li>
      
        
        <li class="menu-item menu-item-life">
          <a href="/categories/life/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            生活
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://eryangboy.github.io/notes/notes/functional-programming/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/favicon.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="二羊的小窝仔">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">函数式编程与 JS 异步编程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-12T16:34:41+08:00">
                2020-12-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/notes/" itemprop="url" rel="index">
                    <span itemprop="name">notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_value_page_pv"></span>次阅读


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h1><ul>
<li>对运算过程进行抽象，用来描述数据(函数)的映射</li>
<li>不是程序中的方法，而是数学中的函数</li>
</ul>
<ol>
<li><p>函数是一等公民：</p>
<ul>
<li>函数可以存在变量中</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> fn = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">&#x27;hello&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<a id="more"></a>
</li>
</ol>
<ul>
<li>函数作为参数</li>
</ul>
<figure class="highlight zephir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">functionforEach (<span class="keyword">array</span>, <span class="function"><span class="keyword">fn</span>) </span>&#123;</span><br><span class="line">   <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="keyword">array</span>.length; i++) &#123;</span><br><span class="line">      <span class="function"><span class="keyword">fn</span><span class="params">(<span class="keyword">array</span>[i])</span></span></span><br><span class="line"><span class="function">   &#125;</span></span><br><span class="line"><span class="function">&#125;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>函数作为返回值</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">makeFn</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="keyword">let</span> msg = <span class="string">&#x27;hello&#x27;</span>;</span><br><span class="line">   <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(msg)</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>高阶函数：</p>
<ul>
<li><p>可以把函数作为参数传递给另一个函数</p>
</li>
<li><p>可以把函数作为另一个函数的返回结果</p>
<ul>
<li><p>使用高阶函数的意义：<br>不用关注细节，只关注目标<br>用来抽象通用问题<br>使代码更简洁</p>
</li>
<li><p>常用的高阶函数：forEach，map，filter，every，some，find，findIndex，reduce，sort</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>闭包：</p>
<ul>
<li><p>函数和其周围的状态(词法环境)的引用捆绑在一起形成闭包</p>
</li>
<li><p>可以在另一个作用域中调用一个函数的内部函数并访问到该函数的作用域中的成员</p>
<ul>
<li>闭包的本质：函数在执行的时候会放到一个执行栈上当函数执行完毕之后会从执行栈上移除，但是堆上的作用域成员因为被外部引用不能释放，因此内部函数依然可以访问外部函数的成员</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">makeFn</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="keyword">let</span> msg = <span class="string">&#x27;hello&#x27;</span>;</span><br><span class="line">   <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(msg)</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>纯函数：</p>
<ul>
<li>相同的输入永远会得到相同的输出，而且没有任何可观察的副作用<ul>
<li>好处：可缓存，可测试，并行处理</li>
</ul>
</li>
</ul>
</li>
<li><p>副作用：</p>
<ul>
<li>副作用让一个函数变的不纯(如上例)，纯函数的根据相同的输入返回相同的输出，如果函数依赖于外部的状态就无法保证输出相同，就会带来副作用。<ul>
<li>来源：配置文件，数据库，获取用户输入…</li>
</ul>
</li>
</ul>
</li>
<li><p>柯里化：</p>
<ul>
<li><p>当一个函数有多个参数的时候先传递一部分参数调用它（这部分参数以后永远不变）</p>
</li>
<li><p>然后返回一个新的函数接收剩余的参数，返回结果</p>
<ul>
<li>柯里化可以让我们给一个函数传递较少的参数得到一个已经记住了某些固定参数的新函数</li>
<li>这是一种对函数参数的’缓存’</li>
<li>让函数变的更灵活，让函数的粒度更小</li>
<li>可以把多元函数转换成一元函数，可以组合使用函数产生强大的功能</li>
</ul>
</li>
</ul>
</li>
<li><p>函数组合：</p>
<ul>
<li>函数组合可以让我们把细粒度的函数重新组合生成一个新的函数<ul>
<li>如果一个函数要经过多个函数处理才能得到最终值，这个时候可以把中间过程的函数合并成一个函数</li>
<li>函数就像是数据的管道，函数组合就是把这些管道连接起来，让数据穿过多个管道形成最终结果</li>
<li>函数组合默认是从右到左执行</li>
</ul>
</li>
</ul>
</li>
<li><p>管道</p>
</li>
<li><p>函子</p>
</li>
</ol>
<ul>
<li><p>容器：包含值和值的变形关系，这个变形关系就是函数</p>
</li>
<li><p>函子：是一个特殊的容器，通过一个普通的对象来实现，该对象有 map 方法，map 方法可以运行一个函数对值进行处理（变形关系）</p>
<ul>
<li>函数式编程的运算不直接操作值，而是由函子完成</li>
<li>函子就是一个实现了 map 契约的对象</li>
<li>我们可以把函子想象成一个盒子，这个盒子里封装了一个值</li>
<li>想要处理盒子中的值，我们需要给盒子的 map 方法传递一个处理值的函数（纯函数），由这个函数来对值进行处理</li>
<li>最终 map 方法返回一个包含新值的盒子（函子）</li>
</ul>
</li>
<li><p>MayBe 函子的作用就是可以对外部的空值情况做处理（控制副作用在允许的范围）</p>
</li>
<li><p>异常会让函数变的不纯，Either 函子可以用来做异常处理</p>
</li>
<li><p>IO 函子可以把不纯的动作存储到 _value 中，延迟执行这个不纯的操作(惰性执行)，包装当前的操作纯，IO 函子可以把不纯的动作存储到 _value 中，延迟执行这个不纯的操作(惰性执行)，包装当前的操作纯</p>
</li>
<li><p>Pointed 函子是实现了 of 静态方法的函子，of 方法是为了避免使用 new 来创建对象，更深层的含义是 of 方法用来把值放到上下文 Context（把值放到容器中，使用 map 来处理值）</p>
</li>
<li><p>Monad 函子是可以变扁的 Pointed 函子，IO(IO(x))，一个函子如果具有 join 和 of 两个方法并遵守一些定律就是一个 Monad</p>
</li>
</ul>
<p>&nbsp;</p>
<h1 id="异步编程"><a href="#异步编程" class="headerlink" title="异步编程"></a>异步编程</h1><ol>
<li><p>同步模式与异步模式</p>
<ul>
<li>单线程：在 JS 引擎中负责解释和执行 JavaScript 代码的线程只有一个，一般称它为主线程。但是实际上还存在其他的线程，可以称之为工作线程。JS 的单线程能够提高工作效率。JavaScript 的主要用途是与用户互动，以及操作 DOM，这就决定了它只能是单线程。单线程意味着前一个任务结束，才会执行后一个任务。</li>
<li>同步：在主线程上排队执行的任务，只有前一个任务执行完毕，才能执行后一个任务。如果在函数 A 返回的时候，调用者就能够得到预期的结果（即拿到了预期的返回值或者看到了预期的效果），那么这个函数就是同步的</li>
<li>异步：不进入主线程、而进入”任务队列”（task queue）的任务，只有”任务队列”通知主线程，某个异步任务可以执行了，该任务才会进入主线程执行。如果在函数 A 返回的时候，调用者还不能马上得到预期的结果，而是需要在将来通过一定的手段得到，那么这个函数就是异步的 。</li>
<li>同步与异步的区别：同步可以保证顺序一致，但是容易导致阻塞；异步可以解决阻塞问题，但是会改变顺序性。</li>
</ul>
</li>
<li><p>事件循环与消息队列</p>
<ul>
<li>事件循环：是指主线程重复从消息队列中取消息，执行的过程<br><img src="/notes/notes/functional-programming/img/EventLoop.jpg" alt="事件循环"></li>
<li>消息队列：是一个先进先出的队列，它里面存放这各种消息。<br><img src="/notes/notes/functional-programming/img/TaskQueue.jpg" alt="消息队列"></li>
</ul>
</li>
<li><p>异步编程的几种方式：</p>
<ul>
<li><p>回调地狱：</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ajax(<span class="string">&#x27;XXX1&#x27;</span>, <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line"><span class="regexp">//</span> callback 函数体</span><br><span class="line">ajax(<span class="string">&#x27;XXX2&#x27;</span>, <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="regexp">//</span> callback 函数体</span><br><span class="line">   ajax(<span class="string">&#x27;XXX3&#x27;</span>, <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">         <span class="regexp">//</span> callback 函数体</span><br><span class="line">   &#125;)</span><br><span class="line">&#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li><p>缺点：回调地狱，不能用 try catch 捕获错误，不能 return</p>
</li>
<li><p>回调地狱的根本问题在于：</p>
</li>
<li><p>缺乏顺序性： 回调地狱导致的调试困难，和大脑的思维方式不符</p>
</li>
<li><p>嵌套函数存在耦合性，一旦有所改动，就会牵一发而动全身，即（控制反转）</p>
</li>
<li><p>嵌套函数过多的多话，很难处理错误</p>
</li>
</ul>
</li>
<li><p>Promise：</p>
<figure class="highlight arcade"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">ajax(<span class="string">&#x27;XXX1&#x27;</span>)</span><br><span class="line">   .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="comment">// 操作逻辑</span></span><br><span class="line">   <span class="keyword">return</span> ajax(<span class="string">&#x27;XXX2&#x27;</span>)</span><br><span class="line">   &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="comment">// 操作逻辑</span></span><br><span class="line">   <span class="keyword">return</span> ajax(<span class="string">&#x27;XXX3&#x27;</span>)</span><br><span class="line">   &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="comment">// 操作逻辑</span></span><br><span class="line">   &#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li><p>Promise 就是为了解决 callback 的问题而产生的。</p>
</li>
<li><p>Promise 实现了链式调用，也就是说每次 then 后返回的都是一个全新 Promise，如果我们在 then 中 return ，return 的结果会被 Promise.resolve() 包装</p>
</li>
<li><p>优点：解决了回调地狱的问题</p>
</li>
<li><p>缺点：无法取消 Promise ，错误需要通过回调函数来捕获</p>
</li>
</ul>
</li>
<li><p>Generator：</p>
<figure class="highlight livescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> *fetch() &#123;</span><br><span class="line">   <span class="keyword">yield</span> ajax(<span class="string">&#x27;XXX1&#x27;</span>, () =&gt; &#123;&#125;)</span><br><span class="line">   <span class="keyword">yield</span> ajax(<span class="string">&#x27;XXX2&#x27;</span>, () =&gt; &#123;&#125;)</span><br><span class="line">   <span class="keyword">yield</span> ajax(<span class="string">&#x27;XXX3&#x27;</span>, () =&gt; &#123;&#125;)</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">let</span> <span class="literal">it</span> = fetch()</span><br><span class="line">   <span class="keyword">let</span> result1 = <span class="literal">it</span>.next()</span><br><span class="line">   <span class="keyword">let</span> result2 = <span class="literal">it</span>.next()</span><br><span class="line">   <span class="keyword">let</span> result3 = <span class="literal">it</span>.next()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>特点：可以控制函数的执行，可以配合 co 函数库使用</li>
</ul>
</li>
<li><p>Async/Await：</p>
<figure class="highlight isbl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">async</span> <span class="variable">function</span> <span class="function"><span class="title">test</span>() &#123;</span></span><br><span class="line"><span class="function">   <span class="variable">await</span> <span class="title">fetch</span>(<span class="string">&#x27;XXX1&#x27;</span>)</span></span><br><span class="line">   <span class="variable">await</span> <span class="function"><span class="title">fetch</span>(<span class="string">&#x27;XXX2&#x27;</span>)</span></span><br><span class="line">   <span class="variable">await</span> <span class="function"><span class="title">fetch</span>(<span class="string">&#x27;XXX3&#x27;</span>)</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>async、await 是异步的终极解决方案</p>
</li>
<li><p>优点是：代码清晰，不用像 Promise 写一大堆 then 链，处理了回调地狱的问题</p>
</li>
<li><p>缺点：await 将异步代码改造成同步代码，如果多个异步操作没有依赖性而使用 await 会导致性能上的降低。</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>Promise 异步方案、宏任务/微任务队列</p>
</li>
<li><p>Generator 异步方案、Async/Await 语法糖</p>
</li>
</ol>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/head1.png" alt=" 我啥都没有"/>
        <p>我啥都没有</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/head2.png" alt=" 就是有钱"/>
        <p>就是有钱</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/function/" rel="tag"># function</a>
          
            <a href="/tags/promise/" rel="tag"># promise</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/notes/notes/typescript/" rel="next" title="ES 新特性与 TypeScript、JS 性能优化">
                <i class="fa fa-chevron-left"></i> ES 新特性与 TypeScript、JS 性能优化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/favicon.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
                <a href="/archives">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B"><span class="nav-text">函数式编程</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B"><span class="nav-text">异步编程</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
 <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">二羊</span>

  
</div>

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
     <i class="fa fa-user"></i> 总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     <i class="fa fa-eye"></i>  总访客 <span id="busuanzi_value_site_uv"></span> 人
</span>
</div>





        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>

<!-- 页面点击小红心 -->

